package com.tang.mybatis.executor;

import com.tang.mybatis.constants.Constants;
import com.tang.mybatis.executor.parameter.DefaultParameterHandler;
import com.tang.mybatis.executor.parameter.ParameterHandler;
import com.tang.mybatis.executor.statment.SimpleStatementHandler;
import com.tang.mybatis.executor.statment.StatementHandler;
import com.tang.mybatis.mapping.MappedStatement;
import com.tang.mybatis.session.Configuration;

import java.sql.*;
import java.util.List;

/**
 * @author Tang
 * @classname SimpleExecutor
 * @description [  ]
 * @date 2022/4/8 17:30
 */
public class SimpleExecutor implements Executor {

    /**
     * 数据库连接
     */
    private static Connection connection;

    private Configuration configuration;

    static {
        initConnect();
    }

    public SimpleExecutor(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> doQuery(String statementId, Object[] args) throws SQLException {
        Connection connection = getConnection();
        MappedStatement mappedStatement = configuration.getMappedStatement(statementId);

        // 预编译sql
        StatementHandler statementHandler = new SimpleStatementHandler(mappedStatement);
        PreparedStatement preparedStatement = statementHandler.prepare(connection);

        // 参数设置
        ParameterHandler parameterHandler = new DefaultParameterHandler(args);
        parameterHandler.setParameters(preparedStatement);

        ResultSet resultSet = statementHandler.query(preparedStatement);

        return null;
    }

    @Override
    public void doUpdate(MappedStatement ms, Object parameter) {

    }

    public Connection getConnection() throws SQLException {
        if (null != connection) {
            return connection;
        } else {
            throw new SQLException("无法连接数据库，请检查配置");
        }
    }

    private static void initConnect() {
        String driver = Configuration.getProperty(Constants.DB_DRIVER_CONF);
        String url = Configuration.getProperty(Constants.DB_URL_CONF);
        String username = Configuration.getProperty(Constants.DB_USERNAME_CONF);
        String password = Configuration.getProperty(Constants.db_PASSWORD);
        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}